<template>
  <view class="root">
    <map id="myMap" style="width: 100%; height: 100vh;position: relative;" :latitude="latitude" :longitude="longitude"
      :scale="mapscale" :markers="markers" :enable-3D="true" :enable-satellite='weiXing' :show-location="true"
      @tap="mapTap" :polyline="polyline" :polygons="polygons">
    </map>

    <view class="top-box" v-if="showSetting">
      <image @click="handleResetEdge" :src="baseImgUrl + 'clear-icon.png'" class="clear-item"></image>
    </view>
    <view class="bottom-button-wrapper">
      <u-button text="电子围栏设置" @click="handleShowSettingFence" :custom-style="ColorButton"></u-button>
    </view>


    <u-popup :show="showSetting" :overlay="false" @close="closeSetting" @open="openSetting" closeable>
      <view class="setting-fence">
        <view class="f-item">
          <view class="f-label">
            开启状态
          </view>
          <u-switch v-model="enable"></u-switch>
        </view>
        <u-line></u-line>
        <view class="f-item" @click="handleSetEffectTime">
          <view class="f-label">
            生效时间
          </view>
          <view class="f-value">
            {{timeString}}
            <image :src="baseImgUrl + 'right-more.png'" class="right-more"></image>
          </view>
        </view>
        <u-line></u-line>
        <view class="btn-box">
          <u-button text="保存" :custom-style="ColorButton" @click="handleSaveFence"></u-button>
        </view>
      </view>
    </u-popup>

    <view class="setting-time">
      <u-modal :show="showModal" title="生效时段设置" showCancelButton @cancel="showModal = false" @confirm="handleConfirm">
        <view class="time-wrapper">
          <u-radio-group v-model="timeModel" iconPlacement="left" @change="handleTimeModelChange">
            <view class="radio-content-box">
              <view class="c-item" @click="handleClickItem(1)">
                <u-radio label=" " :name="1"></u-radio>
                <view class="inner-box">
                  <view class="i-label">
                    全天
                  </view>
                  <view class="i-value">
                    24小时对检测设备离开安全围栏报警
                  </view>
                </view>
              </view>
              <view class="c-item" @click="handleClickItem(2)">
                <u-radio label=" " :name="2"></u-radio>
                <view class="inner-box">
                  <view class="i-label">
                    白天
                  </view>
                  <view class="i-value">
                    8:00到20:00对检测设备离开安全围栏报警
                  </view>
                </view>
              </view>
            </view>
          </u-radio-group>

          <smh-time-range :time="timeList" ref="timeRef"></smh-time-range>

        </view>
      </u-modal>
    </view>
    <yy-watermark></yy-watermark>
  </view>
</template>

<script>
  import {
    wbHttpFences
  } from '../api/api'
  import {
    getAction
  } from '../utils/request'
  import {
    ConvexHull,
    getOptionsParams,
    isLoading,
    ColorButton,
    Toast,
    compareTime
  } from '../utils/util'
  import {
    nextTick
  } from "vue"
  import _ from '@/utils/lodash.js'

  export default {
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        mapscale: 14,
        markers: [],
        weiXing: false,
        controls: [],
        polygons: [],
        polyline: [],
        routerParams: {},

        startTime: "00:00",
        startDefaultTime: "00:00",
        endTime: "24:00",
        endDefaultTime: "24:00",

        timeRef: null,
        showModal: false,
        timeModel: '1',
        timeSlot: [],
        ColorButton,
        showSetting: false,
        enable: true,
        timeString: '',
        details: {},
        timeList: ['12', '30', '0', '17', '30'],
        canSetPoint: false
      }
    },
    onLoad(options) {
      this.routerParams = getOptionsParams(options)
      this.initPage()
    },
    methods: {
      initPage() {
        isLoading(true)
        getAction('/mini/wb/deviceinfo/setFance', {
            imei: this.routerParams.imei
          })
          .then((res) => {
            const result = res.result
            this.details = {
              ...result
            }
            this.enable = result.enable == 1 ? true : false
            const timesStr = `${result.timeBegin}-${result.timeEnd}`
            // 字符串判断
            if (timesStr == '00:00-24:00') {
              this.timeString = '全天'
            } else if (timesStr == '08:00-20:00') {
              this.timeString = '白天'
            } else {
              this.timeString = timesStr
            }

            let tempTime = [...this.timeList]
            this.$nextTick(() => {
              let start = this.details.timeBegin.split(':')
              let end = this.details.timeEnd.split(':')

              tempTime[0] = start[0]
              tempTime[1] = start[1]
              tempTime[3] = end[0]
              tempTime[4] = end[1]
              this.timeList = tempTime
            })

            let points = []
            if (true) {
              points = [{
                  longitude: result.pos1Lon,
                  latitude: result.pos1Lat,
                },
                {
                  longitude: result.pos2Lon,
                  latitude: result.pos2Lat,
                },
                {
                  longitude: result.pos3Lon,
                  latitude: result.pos3Lat,
                },
                {
                  longitude: result.pos4Lon,
                  latitude: result.pos4Lat,
                }
              ]
              const personLocation = {
                longitude: this.routerParams.lon,
                latitude: this.routerParams.lat
              }
              // 拿到点之后渲染
              this.onMapLoaded(points, personLocation)
            }
          })
          .finally(() => {
            isLoading(false)
          })
      },
      onMapLoaded(points, personLocation) {
        this.mapContext = uni.createMapContext('myMap', this);
        // 在地图加载完成后，将地图的中心点设置为标记的位置
        this.drawRectangle(points, personLocation);
        this.mapContext.includePoints({
          points: [...points,
            {
              latitude: personLocation.latitude,
              longitude: personLocation.longitude
            }
          ],
          padding: [50, 50, 50, 50]
        });
      },
      drawRectangle(points, personLocation) {
        // 先清空 再 push
        this.markers = []
        this.polygons = []
        this.polyline = []
        // 添加人 点
        this.markers.push({
          id: this.markers.length + 1,
          latitude: personLocation.latitude,
          longitude: personLocation.longitude,
          iconPath: this.baseImgUrl + 'person-01.png',
          width: 45,
          height: 48,
        })

        const paths = points.map(point => {
          const {
            longitude,
            latitude
          } = point
          // 添加 marker 点
          this.markers.push({
            id: this.markers.length + 1,
            latitude,
            longitude,
            iconPath: '/static/icons/area-icon.png',
            width: 15,
            height: 27,
          })

          return {
            longitude,
            latitude
          }
        });



        this.polygons = [{
          points: paths,
          strokeWidth: 1,
          strokeColor: '#FC6F2E',
          fillColor: '#F98E3047',
        }];
      },
      show() {
        this.$refs['time'].open();
      },
      timeRange(e) {
        console.log(e);
      },
      handleClickItem(val) {
        this.timeModel = val
        // 全天
        let tempTime = [...this.timeList]

        if (val == 1) {
          tempTime[0] = '00'
          tempTime[1] = '00'
          tempTime[3] = '24'
          tempTime[4] = '00'
        } else if (val == 2) {
          tempTime[0] = '08'
          tempTime[1] = '00'
          tempTime[3] = '20'
          tempTime[4] = '00'
        }
        this.timeList = tempTime
      },
      handleTimeModelChange(name) {
        this.handleClickItem(name)
      },
      handleConfirm() {
        let times = this.$refs.timeRef.getTime()
        this.timeSlot = times
        let timesStr = `${times[0]}:${times[1]}-${times[2]}:${times[3]}`

        // 要判断结束时间不能大于开始时间
        let time1 = `${times[0]}:${times[1]}`
        let time2 = `${times[2]}:${times[3]}`
        console.log(time1, time2)
        if (compareTime(time1, time2) != -1) {
          Toast('开始时间不能大于结束时间！')
          return
        }
        if (timesStr == '00:00-24:00') {
          this.timeString = '全天'
        } else if (timesStr == '08:00-20:00') {
          this.timeString = '白天'
        } else {
          this.timeString = timesStr
        }
        this.showModal = false
      },
      closeSetting() {
        this.showSetting = false
      },
      openSetting() {
        this.showSetting = true
      },
      handleSetEffectTime() {
        // 
        this.showModal = true

      },
      handleResetEdge() {
        if (this.routerParams.thisIsResponsible == 0) {
          Toast('非主要负责人，暂无权限设置！')
          return
        }
        this.markers = this.markers.splice(0, 1)
        this.polyline = []
        this.polygons = []
        this.canSetPoint = true
      },
      mapTap(e) {
        const {
          longitude,
          latitude
        } = e.detail
        if (this.markers.length < 5) {
          this.markers.push({
            id: this.markers.length + 1,
            latitude,
            longitude,
            iconPath: '/static/icons/area-icon.png',
            width: 20,
            height: 20,
          })
        }
        if (this.markers.length == 5) {

          // 开始绘制
          console.log(this.markers)
          let points = this.markers.slice(1, this.markers.length)
          let paths = points.map(item => {
            const {
              latitude,
              longitude,
            } = item
            return {
              latitude,
              longitude,
            }
          })

          let ploygonList = paths.map((tempItem) => {
            return {
              ...tempItem,
              x: tempItem.latitude,
              y: tempItem.longitude,
            }
          })
          ploygonList = ConvexHull(ploygonList)

          paths = ploygonList.map(item => {
            const {
              latitude,
              longitude,
            } = item
            return {
              latitude,
              longitude,
            }
          })
          this.polygons = [{
            points: paths,
            strokeWidth: 1,
            strokeColor: '#FC6F2E',
            fillColor: '#F98E3047',
          }];
          this.canSetPoint = false
          return
        }
      },
      handleSaveFence() {
        let points = _.get(this.polygons, '[0].points', [])
        if (points.length < 4) {
          Toast('围栏坐标不能为空，或不满足4个点！')
          return
        }
        let times = this.$refs.timeRef.getTime()
        let start = `${times[0]}:${times[1]}`
        let end = `${times[2]}:${times[3]}`
        let pos = this.polygons[0].points.slice(0, 4).reduce((acc, curr, index) => {
          acc[`pos${index + 1}Lon`] = curr.longitude
          acc[`pos${index + 1}Lat`] = curr.latitude
          return acc
        }, {})
        const params = {
          freq: 1,
          timeBegin: start,
          timeEnd: end,
          deviceId: this.details.deviceId,
          imei: this.routerParams.imei,
          type: 0, // 不删除
          enable: this.enable ? 1 : 0,
          ...pos,
        }
        isLoading(true)
        wbHttpFences(params)
          .then((res) => {
            setTimeout(() => {
              Toast('保存成功！')
            }, 300)
            this.showSetting = false
            this.initPage()
          })
          .finally(() => {
            isLoading(false)
          })
      },
      handleShowSettingFence() {
        if (this.routerParams.thisIsResponsible == 0) {
          Toast('非主要负责人，暂无权限设置！')
          return
        }
        this.showSetting = true
      }
    }
  }
</script>

<style lang="scss" scoped>
  .time-wrapper {
    display: flex;
    flex-direction: column;
  }

  .radio-content-box {
    display: flex;
    flex-direction: column;
    width: 100%;
    padding: 0rpx 50rpx;
    margin-bottom: 10rpx;

    .c-item {
      display: flex;
      border-bottom: 1px solid rgb(236, 238, 237);
      padding: 10rpx 0;

      .inner-box {
        margin-right: 8rpx;
      }
    }
  }

  .root {
    position: relative;
    width: 100%;
    height: 100%;

    .top-box {
      position: absolute;
      top: 20rpx;
      right: 20rpx;
      display: flex;

      .clear-item {
        width: 197rpx;
        height: 64rpx;
      }


      .edge-box {
        font-weight: 500;
        font-size: 28rpx;
        color: #FC590E;
        border: 1px solid #FC590E;
        border-radius: 36rpx;
        padding: 4rpx 15rpx;
        display: flex;
        align-items: center;
        margin-left: 10rpx;
        background: #fff;
      }

    }

    .bottom-button-wrapper {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
    }

    .setting-fence {
      padding: 0 50rpx;
      padding-top: 40rpx;

      .f-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 35rpx 0;

        .f-label {
          font-weight: bold;
          font-size: 30rpx;
          color: #000000;
        }

        .switch-box {
          display: flex;
          width: 50rpx;
        }

        .f-value {
          font-weight: bold;
          font-size: 30rpx;
          color: #1A1A1A;
          display: flex;
          align-items: center;

          .right-more {
            width: 14rpx;
            height: 27rpx;
            margin-left: 13rpx;
          }
        }
      }

      .btn-box {
        padding-bottom: 20rpx;
        padding-top: 80rpx;

        /deep/ .u-button__text {
          font-size: 32rpx !important;
          font-weight: bold !important;
        }
      }
    }

    .setting-time {
      /deep/.u-popup {
        .u-transition {
          z-index: 200000 !important;
        }
      }

      /deep/.u-modal__content {
        padding: 20rpx 0;
      }
    }
  }
</style>